<template>
    <div class="retrieve-container">
        <el-card class="retrieve-card">
            <template #header>
                <div class="card-header">
                    <span>密码找回</span>
                </div>
            </template>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="auto">
                <el-form-item label="邮箱" prop="email">
                    <el-input clearable v-model="form.email" placeholder="请输入注册邮箱"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <el-input clearable v-model="form.code" placeholder="请输入验证码"></el-input>
                    <el-button @click="sendCode" :disabled="isSendingCode" style="margin-top: 5px">
                        {{ isSendingCode ? `${countDown}s 后重试` : '发送验证码' }}
                    </el-button>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input clearable show-password v-model="form.newPassword" type="password" placeholder="请输入新密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input clearable show-password v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm" block>提交</el-button>
                </el-form-item>
            </el-form>
            <template #footer>
                <!-- 前往登录 -->
                <el-link type="primary" @click="toLogin">前往登录</el-link>
            </template>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { findPassword } from '@/api/email';
import { changePassword } from '@/api/user';
import { FormInstance, FormRules } from 'element-plus';

// 表单引用
const formRef = ref<FormInstance>();
// 表单数据
const form = reactive({
    email: '',
    code: '',
    newPassword: '',
    confirmPassword: '',
});

// 表单验证规则
const rules = reactive<FormRules<typeof form>>({
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
    ],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于 6 位', trigger: 'blur' },
    ],
    confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
            validator: (_rule, value, callback) => {
                if (value !== form.newPassword) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur',
        },
    ],
});

// 发送验证码相关
const isSendingCode = ref(false);
const countDown = ref(60);
let timer: NodeJS.Timeout | null = null;

// 发送验证码
const sendCode = async () => {
    if (!formRef.value) return;
    await formRef.value.validateField('email');
    if (!form.email) return;

    isSendingCode.value = true;
    timer = setInterval(() => {
        countDown.value--;
        if (countDown.value <= 0) {
            clearInterval(timer as NodeJS.Timeout);
            isSendingCode.value = false;
            countDown.value = 60;
        }
    }, 1000);

    // 这里添加实际发送验证码的逻辑

    findPassword(form.email).then((res) => {
        ElMessage.success(res.message);
    });
};

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;
    await formRef.value.validate((valid) => {
        if (valid) {
            // 这里添加实际提交表单的逻辑
            changePassword(form.newPassword, form.email, form.code).then((res) => {
                // 弹窗提示
                ElMessageBox.confirm(res.message, '提示', {
                    confirmButtonText: '确定',
                    type: 'success',
                }).then(() => {
                    // 弹窗关闭后，前往登录
                    router.push({ name: 'Login' });
                });
            });
        } else {
            ElMessage.error('表单验证失败，请检查输入');
        }
    });
};

// 前往登录
const router = useRouter();
const toLogin = () => {
    router.push({ name: 'Login' });
};
</script>

<style scoped>
.retrieve-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
}

.retrieve-card {
    width: 400px;
}

.card-header {
    display: flex;
    justify-content: center;
    font-size: 18px;
    font-weight: bold;
}
</style>
